package com.hd.crdao.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.MessageEvent;
import com.hd.crdao.bean.MsgBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.ChineseUtils;
import com.hd.crdao.utils.GlobalData;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/6/26 0026
 */
public class CreateShopActivity extends BaseSecondActivity implements View.OnClickListener {


    private static final int FROM_CAMERA = 103;
    private static final int FROM_PIC = 104;


    public int count;
    public ArrayList<String> imagePaths = new ArrayList<>();
    @BindView(R.id.createshop_head)
    ExpandHeadView mCreateshopHead;
    @BindView(R.id.shop_icon)
    ImageView mShopIcon;
    @BindView(R.id.shop_name)
    EditText mShopName;
    @BindView(R.id.shop_address)
    TextView mShopAddress;
    @BindView(R.id.inputaddress)
    LinearLayout mInputAddress;
    @BindView(R.id.shop_telephone)
    EditText mShopTelephone;
    @BindView(R.id.openshoptime)
    TextView mOpenshoptime;
    @BindView(R.id.closeshoptime)
    TextView mCloseshoptime;
    @BindView(R.id.shop_introduction)
    EditText mShopIntroduction;
    @BindView(R.id.shop_indeximage)
    ImageView mShopIndeximage;
    @BindView(R.id.btnSubmit_createshop)
    Button mBtnSubmitCreateshop;
    private String location;


    @Override
    protected int setContentView() {
        return R.layout.activity_createshop;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mCreateshopHead;
    }

    @Override
    protected void initView() {
        initEvent();
        EventBus.getDefault().register(this);
        String redisplayAddress = SPUtils.getString("redisplayAddress", "");
        mShopAddress.setText(redisplayAddress);
        String phoneNumber = SPUtils.getString("phoneNumber", "");
        mShopTelephone.setText(phoneNumber);
    }


    /**
     * 初始化
     */
    private void initEvent() {
        imagePaths.add(0, "");
        imagePaths.add(1, "");
        mShopIcon.setOnClickListener(this);
        mShopIndeximage.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shop_icon:
                count = 0;
                upLoadIdcardImage();
                break;
            case R.id.shop_indeximage:
                count = 1;
                upLoadIdcardImage();
                break;
        }
    }

    /**
     * 上传证件照片
     */
    private void upLoadIdcardImage() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);

        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开系统照相机
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, FROM_CAMERA);
                popWindow.dismiss();
            }
        });
        btnAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从系统相册中获取照片
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, FROM_PIC);
                popWindow.dismiss();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }


    /**
     * 返回结果中拿到图片路径并赋值
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FROM_CAMERA && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                String fileName = GlobalData.tempImagePaht + "/" + System.currentTimeMillis() + ".jpg";
                ALog.d(fileName);
                try {
                    FileOutputStream fos = new FileOutputStream(fileName);
                    assert bitmap != null;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    fos.flush();
                    fos.close();
                    ALog.d("照片已保存到：" + fileName);
                    if (count == 0) {
                        /*Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.logo_moren_2x)
                                .bitmapTransform(new GlideCircleTransform()).into(mShopIcon);*/
                        GlideImageUtils.loadImage(fileName,R.drawable.logo_moren_2x,true,mShopIcon);
                    } else if (count == 1) {
                      /*  Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.logo_moren_2x)
                                .bitmapTransform(new GlideCircleTransform())
                                .into(mShopIndeximage);*/
                        GlideImageUtils.loadImage(fileName,R.drawable.logo_moren_2x,true,mShopIndeximage);
                    }
                    imagePaths.set(count, fileName);
                    bitmap.recycle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //从图库选择返回的结果
        if (requestCode == FROM_PIC && resultCode == RESULT_OK) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imagePath = cursor.getString(columnIndex);
                if (count == 0) {
                  /*  Glide.with(UIUtils.getContext()).load(imagePath).placeholder(R.drawable.logo_moren_2x)
                            .bitmapTransform(new GlideCircleTransform())
                            .into(mShopIcon);*/
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,true,mShopIcon);
                } else if (count == 1) {
                   /* Glide.with(UIUtils.getContext()).load(imagePath).placeholder(R.drawable.logo_moren_2x)
//                              .bitmapTransform(new GlideCircleTransform())
                            .into(mShopIndeximage);*/
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,true,mShopIndeximage);
                }

                ALog.d(imagePath);
                imagePaths.set(count, imagePath);
                cursor.close();
            }
        }


    }


    @OnClick({R.id.openshoptime, R.id.closeshoptime, R.id.btnSubmit_createshop, R.id.inputaddress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.inputaddress:
                ALog.d("选择地址");
                Intent intent = new Intent(UIUtils.getContext(), ChangeAddressActivity.class);
                intent.putExtra("selectlevel", Config.SELECTAREA);
                String allAddress = mShopAddress.getText().toString().trim();
                intent.putExtra("allAddress", StringUtils.ParseAddress(allAddress));
                startActivity(intent);
                break;
            case R.id.openshoptime:
                timeSelected("开店时间", mOpenshoptime);
                break;
            case R.id.closeshoptime:
                timeSelected("闭店时间", mCloseshoptime);
                break;
            case R.id.btnSubmit_createshop:
                //检查信息是否成功

                String shopName = mShopName.getText().toString().trim();
                String storeAddress = mShopAddress.getText().toString().trim();
                String storeMobile = mShopTelephone.getText().toString().trim();
                String opentime = mOpenshoptime.getText().toString().trim();
                String closetime = mCloseshoptime.getText().toString().trim();
                String storeProfile = mShopIntroduction.getText().toString().trim();
                String areaId = SPUtils.getString(Config.areaId, "");
                if (TextUtils.isEmpty(location)) {
                    location = SPUtils.getString(Config.cbLocation, "");
                }
                if (checkShopInfo(shopName, storeAddress, storeMobile, opentime, closetime, storeProfile, areaId)) {
                    StyledDialog.buildMdLoading().setActivity(this).show();
                    upLoadSomeInformations(shopName, storeAddress, storeMobile, opentime, closetime, storeProfile, areaId, location);
                }
                break;
        }
    }

    /**
     * 检查信息是否填写完整
     *
     * @param shopName
     */
    private boolean checkShopInfo(String shopName, String storeAddress,
                                  String storeMobile, String opentime, String closetime, String storeProfile, String areaId) {

        if (TextUtils.isEmpty(shopName)) {
            MyToast.show("请填写店铺名称");
            return false;
        } else if (!ChineseUtils.checkNameChese(shopName)) {
            MyToast.show("请输入中文的店铺名称");
            return false;
        }
        if (TextUtils.isEmpty(storeAddress)) {
            MyToast.show("请填写店铺地址");
            return false;
        }
        if (TextUtils.isEmpty(storeMobile)) {
            MyToast.show("请填写手机号码");
            return false;
        }
        if (TextUtils.isEmpty(opentime)) {
            MyToast.show("请填写开店时间");
            return false;
        }
        if (TextUtils.isEmpty(closetime)) {
            MyToast.show("请填写闭店时间");
            return false;
        }
        return true;


    }

    private void upLoadSomeInformations(String shopName, String storeAddress, String storeMobile, String opentime,
                                        String closetime, String storeProfile, String areaId, String location) {
        try {
            String businessid = SPUtils.getString(Config.businessId, "");
            HashMap<String, String> map = new HashMap<>();
            map.put("sign", Constants.SIGN);
            map.put("carBusinessId", businessid);
            map.put("storeName", shopName);
            map.put("storeAddress", storeAddress);
            map.put("storeMobile", storeMobile);
            map.put("businessHours", opentime + "," + closetime);
            map.put("storeLatlon", location);
            map.put("areaId", areaId);
            if (!TextUtils.isEmpty(storeProfile)) {
                map.put("storeProfile", storeProfile);
            }
            PostFormBuilder params = OkHttpUtils.post().url(Constants.CREATEANDUPDATESHOP_URL).params(map);
            if (!TextUtils.isEmpty(imagePaths.get(0))) {
                params.addFile("storeLogo", imagePaths.get(0), new File(imagePaths.get(0)));
            }
            if (!TextUtils.isEmpty(imagePaths.get(1))) {
                params.addFile("storeImage", imagePaths.get(1), new File(imagePaths.get(1)));
            }
            params.build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyToast.show("网络开了个小差");
                    StyledDialog.dismissLoading();
                }

                @Override
                public void onResponse(String response, int id) {
                    ALog.d(response);
                    MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                    if (msgBean.getSuccess() == 0) {
                        MyToast.show(msgBean.getMessage());
                        StyledDialog.dismissLoading();
                        startActivity(new Intent(UIUtils.getContext(), MyShopActivity.class));
                        finish();
                    } else {
                        MyToast.show(msgBean.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            e.getMessage();
        }

    }


    /**
     * 时间选择器
     *
     * @param title
     * @param textView
     */
    private void timeSelected(String title, final TextView textView) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                textView.setText(String.valueOf(new SimpleDateFormat("HH:mm", Locale.CHINESE).format(date)));
            }
        })
                .setType(new boolean[]{false, false, false, true, true, false})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.parseColor("#2e2e2e"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#2e2e2e"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#2e2e2e"))//取消按钮文字颜色
                .setTitleBgColor(0x000000)//标题背景颜色 Night mode
                .setBgColor(0x000000)//滚轮背景颜色 Night mode
                .setDate(Calendar.getInstance())// 默认是系统时间*/
                .setLabel(null, null, null, "时", "分", null)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getLocation(MessageEvent messageEvent) {
        mShopAddress.setText(messageEvent.getAddress());
        location = messageEvent.getLocation();
        ALog.d(messageEvent.getAddress());
        ALog.d(messageEvent.getLocation());
    }


}
